<?php

namespace App\Service\VendorClient\Shoptangshangang;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

/**
 * 唐山港跨境云上游对接SDK
 * @author hj
 */
class ShoptangshangangApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shoptangshangang';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     */
    public function createOrder($param = []) {
        if (empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo'])) {
            return Normal::returnCode(Normal::FAIL, "except param supplierOrder or orderGoods or order or binfo");
        }
        $orderInfo = $param['supplierOrder'];
        $goodsList = $param['orderGoods'];
        $order     = $param['order'];
        $binfo     = $param['binfo'];
        $order_sn  = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //电商平台信息
        $enterpriseNum  = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum  = $order['enterpriseNum'] ?? $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ?? $enterpriseName;
        //支付公司信息
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyName = $apply_extends['payCommanyName'] ?? '';
        $payCommanyCode = $order['payCommanyCode'] ?? $payCommanyCode;
        $payCommanyName = $order['payCommanyName'] ?? $payCommanyName;
        //获取下单商品信息
        $palceOrderGoods    = [];
        $totalGoodsMoney    = '0.00';
        $goodsTotalMoney    = '0.00';
        $goodsTotalMoneyNot = '0.00';
        $wayTaxFee          = '0.00';
        foreach ($goodsList as $key => $item) {
            $tax_rate         = bcadd('1', (string)$item['tax_rate'], 4);
            $price            = $item['price'];
            $spec_num         = $item['spec_num'];
            $quantity         = $item['quantity'];
            $supplier_skucode = $item['supplier_skucode'];
            $goods_type       = $item['goods_type'];
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount = $spec_num * $quantity;
            // if ($key == 0) {
            //     $singleDeliveryMoney = bcdiv((string)$deliver_money, (string)$quantity, 3);
            //     $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney, (string)100, 1);
            //     $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100, 2);
            //     $price               = bcadd((string)$price, (string)$singleDeliveryMoney, 2);
            // }
            //不含税价格
            $singleGoodsPrice = bcdiv((string)$price, (string)$tax_rate, 3);
            $singleGoodsPrice = bcmul((string)$singleGoodsPrice, (string)100, 1);
            $singleGoodsPrice = bcdiv((string)ceil($singleGoodsPrice), (string)100, 2);
            //商品不含税总价
            $goodsTotalPrice = bcmul((string)$singleGoodsPrice, (string)$quantity, 2);
            //含税总价
            $goodsTotalPriceTax = bcmul((string)$price, (string)$quantity, 2);
            //税费
            $tax    = bcsub((string)$price, (string)$singleGoodsPrice, 2);
            $taxAll = bcmul((string)$tax, (string)$quantity, 2);
            //判断是不是保税订单
            $taxAll = $goods_type == 1 ? $taxAll : 0;
            //不含税总金额
            $goodsTotalMoneyNot = bcadd((string)$goodsTotalMoneyNot, (string)$goodsTotalPrice, 2);
            //含税总金额
            $goodsTotalMoney = bcadd((string)$goodsTotalMoney, (string)$goodsTotalPriceTax, 2);
            //总税费
            $wayTaxFee = bcadd((string)$wayTaxFee, (string)$taxAll, 2);
            //下单商品组
            $goodsInfo         = [
                'goodsIndex'   => $key + 1,//顺序号
                'ebpGoodsNo'   => $item['supplier_skucode'],//电商商品货号
                'ebpGoodsName' => $item['goods_name'],//商品名称
                'ebpPrice'     => $singleGoodsPrice,//单价 不含税
                'ebpQty'       => (int)$quantity,//数量
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        $totalMoney = bcadd((string)$goodsTotalMoney, (string)$deliver_money, 2);
        //用户实际支付金额
        $real_total_money = $orderInfo['real_total_money'];
        //订单优惠金额
        $discount_money = bcsub((string)$totalMoney, (string)$real_total_money, 2);
        $requestParam   = [
            'platformOrderNo'    => $order_sn,//平台订单号
            'declareNo'          => $order_sn,//清关订单号
            'orderTime'          => $order_time,//下单时间
            'payTime'            => $pay_time,//支付时间
            'payTransactionId'   => $order['paySerial'] ?? $apply_extends['paySerial'],//支付单号
            'ebpPayCode'         => $payCommanyCode,//支付方式(参考附录3)
            'buyerRegNo'         => $orderInfo['buyer_phone'],//订购人注册号
            'buyerIdNumber'      => $orderInfo['buyer_idcard'],//订购人身份证号
            'buyerName'          => $orderInfo['buyer_realname'],//订购人姓名
            'buyerTelephone'     => $orderInfo['buyer_phone'],//订购人手机
            'consigneeProvince'  => $orderInfo['province'],//收件人省
            'consigneeCity'      => $orderInfo['city'],//收件人市
            'consigneeArea'      => $orderInfo['district'],//收件人区
            'consigneeAddress'   => $orderInfo['province'] . $orderInfo['city'] . $orderInfo['district'] . $orderInfo['receive_address'],//收件人完整地址(包含省市区街道)
            'consignee'          => $orderInfo['receive_name'],//收件人
            'consigneeTelephone' => $orderInfo['recveive_phone'],//收件人电话
            'freight'            => $deliver_money,//运费
            'discount'           => $discount_money > 0 ? $discount_money : '0.00',//抵扣金额
            'tax'                => $wayTaxFee,//税费(如果没有则填0)
            'goodsValue'         => $goodsTotalMoneyNot,//商品总价
            'payfee'             => $real_total_money,//实际支付金额
            'ebpCode'            => $enterpriseNum,//电商平台代码
            'ebpName'            => $enterpriseName,//电商平台名称(电商企业代码不为空时必填)
            'buyerMemo'          => $orderInfo['order_remark'],//买家留言
            'shopMemo'           => $orderInfo['order_remark'],//商家备注
            'goodsList'          => $palceOrderGoods,//商品列表
        ];
        $data           = [
            'method' => 'createOrder',
            'data'   => json_encode($requestParam, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ];
        return $this->execute($data);
    }

    /**
     * 获取取消订单
     */
    public function cancelOrder($params = []) {
        $queryParam = [
            'platformOrderNo' => $params['supplierOrder']['supplier_dsn'],//单号
        ];
        $data       = [
            'method' => 'cancelOrder',
            'data'   => json_encode($queryParam, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ];
        return $this->execute($data);
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data) {
        ksort($data);
        $strA = '';
        foreach ($data as $k => $v) {
            $strA .= "{$k}{$v}";
        }
        $strB = $this->config['appSecret'] . $strA . $this->config['appSecret'];
        return md5(strtolower($strB));
    }

    /**
     * CURL请求
     * @param $params
     * @return array
     */
    public function execute($param = []) {
        $method = $param['method'];
        $data   = $param['data'];
        if (!isset($this->config[$method])) {
            return Normal::returnCode(Normal::FAIL, "请求方法名称未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "接口请求数据不能为空");
        }
        $url = $this->config['baseUrl'] ?? '';
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口请求地址不能为空");
        }
        $pushData         = [
            'method'     => $this->config[$method],//接口名称
            'appkey'     => $this->config['appKey'],
            'timestamp'  => time(),
            'bizcontent' => $param['data']
        ];
        $pushData['sign'] = $this->sign($pushData);
        $parameter        = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => [],
            ],
        ];
        $resTask          = TaskWorker::instance()->addTask($parameter);
        $resTask          = current($resTask);
        $result           = @json_decode($resTask['response']['result'], true);
        if (isset($result['success']) && $result['success'] == false) {
            $msg = $result['msg'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg);
        }
        if (isset($result['code']) && $result['code'] != '0') {
            $msg = $result['msg'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg);
        }
        return Normal::returnCode(Normal::SUC, "调用成功", $result);
    }


}